import 'dart:math';

import 'package:flutter/material.dart';
import 'model.dart';

class StateManager with ChangeNotifier {
  late List<TabModel> _tabs;

  List<List<TextEditingController>> answerControllers = [];

  // 初始化加点示例数据
  StateManager() {
    // 给一个示例数据
    _tabs = _makeExample();
    for (var tab in _tabs) {
      var arr = <TextEditingController>[];
      for (var q in tab.questions) {
        arr.add(TextEditingController(text: q.answer));
      }
      answerControllers.add(arr);
    }
    // 默认选中第一个tab
    setActiveIndex(0);
  }

  List<TabModel> get tabs => _tabs;
  // 当前选中的tab序号
  int activeIndex = 0;
  // 当前选中的tab
  TabModel get currentTab => _tabs[activeIndex];

  void setActiveIndex(int index) {
    activeIndex = index;
    notifyListeners();
  }

  void addTab([String name = "Reading"]) {
    _tabs.add(TabModel(name: name, questions: []));
    answerControllers.add([]);
    notifyListeners();
  }

  void removeTab(int i) {
    if (_tabs.length <= 1) return;
    _tabs.removeAt(i);
    if (i <= activeIndex) {
      activeIndex = max(activeIndex - 1, 0);
    }

    for (var e in answerControllers[i]) {
      e.dispose();
    }
    answerControllers.removeAt(i);
    notifyListeners();
  }

  void addQuestion() {
    currentTab.questions.add(QuestionModel(must: true));
    answerControllers[activeIndex].add(TextEditingController());
    notifyListeners();
  }

  void removeQuestion(int i) {
    currentTab.questions.removeAt(i);
    answerControllers[activeIndex][i].dispose();
    answerControllers[activeIndex].removeAt(i);
    notifyListeners();
  }

  void onAnswerChanged(String value, int index) {
    currentTab.questions[index].answer = value;
    notifyListeners();
  }

  /// 生成示例数据，用作作业页面初始化后调用，不至于打开完全空白
  static List<TabModel> _makeExample() {
    // 此处的json数据为初始数据，实际应用中需要从api获取数据
    const List<Map<String, dynamic>> json = [
      {
        "name": "Vocabulary",
        "questions": [
          {"question": "Write a short story about yourself."},
          {"question": "Write a short story about yourself."},
          {"question": "Write a short story about yourself."},
        ]
      },
      {
        "name": "Sentence",
        "questions": [
          {
            "question":
                "What is the difference between a noun and a verb difference between a noun and a verb? What is the difference between a noun a"
          }
        ]
      },
      {
        "name": "Writing",
        "questions": [
          {
            "question": " Topic",
            "placeholder": "The  topic has not been filled in"
          }
        ]
      }
    ];
    return json.map((e) => TabModel.fromJson(e)).toList();
  }
}
